<?php
/**
 * UserActivityLogBehaviour
 *
 * @author    Evgeny Utehin <utehin@ebola.com.ua>
 * @copyright Copyright &copy; 2014 Ebola Communications
 * @link      http://www.ebola.com.ua/
 *
 * @var _oldAttributes array
 * @var _newAttributes array
 */
class UserActivityLogBehaviour extends CActiveRecordBehavior
{
    const CREATE_ACTION = 'create';
    const UPDATE_ACTION = 'update';
    const DELETE_ACTION = 'delete';

    protected $_oldAttributes;
    protected $_newAttributes;

    /**
     * @see CActiveRecordBehavior::afterSave($event)
     */
    public function afterSave($event)
    {
        $this->_newAttributes = $this->Owner->getAttributes();

        if ($this->Owner->isNewRecord) {
            $this->saveLog(self::CREATE_ACTION);
        } else {
            $this->saveLog(self::UPDATE_ACTION);
        }
    }

    /**
     * @see CActiveRecordBehavior::afterDelete($event)
     */
    public function afterDelete($event)
    {
        $this->saveLog(self::DELETE_ACTION);
    }

    /**
     * @see CActiveRecordBehavior::afterFind($event)
     */
    public function afterFind($event)
    {
        $this->setOldAttributes($this->Owner->getAttributes());
    }

    /**
     * Getter for _oldAttributes
     *
     * @return array
     */
    protected function getOldAttributes()
    {
        return $this->_oldAttributes;
    }

    /**
     * Setter for _oldAttributes
     *
     * @param array
     */
    protected function setOldAttributes($value)
    {
        $this->_oldAttributes = $value;
    }

    /**
     * Save record to user_actvivity table
     *
     * @param  action string
     * @throws Exception if no authorized users found
     * @throws Exception if cant save log record
     */
    protected function saveLog($action)
    {
        if (Yii::app()->user->isGuest) {
            throw new Exception(get_class($this) . ": no authorized users found.");
        } else {
            $log = new UserActivity;

            $log->entity        = get_class($this->Owner);
            $log->entity_id     = $this->Owner->getPrimaryKey();
            $log->user_id       = Yii::app()->user->id;
            $log->action        = $action;
            $log->description   = 'User ' . Yii::app()->user->Name . ' ' . $action . ' '
                . get_class($this->Owner) . '[' . $this->Owner->getPrimaryKey() .'].';
            $log->previous_data = is_null($this->_oldAttributes) ? $this->_oldAttributes : serialize($this->_oldAttributes);
            $log->current_data  = is_null($this->_newAttributes) ? $this->_newAttributes : serialize($this->_newAttributes);

            if (!$log->save()) {
                throw new Exception(get_class($this) . ": cant save log record.");
            }
        }
    }
}
